<template>
  <div class="use">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索区域 -->
    <div style="margin-top: 15px;">
      <el-input
        @input="init"
        placeholder="请输入内容"
        v-model="userobj.query"
        class="input-with-select"
        style="width:300px; margin-right:10px"
      >
        <el-button slot="append" icon="el-icon-search" @click="init"></el-button>
      </el-input>
      <el-button type="success" @click="addDialogFormVisible=true">添加用户</el-button>
    </div>
    <!-- 表格展示区域 -->
    <el-table border :data="userList" style="width: 100%;margin-top:10px">
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column prop="username" label="姓名" width="180"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <el-table-column label="用户状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change='changeState(scope.row.id,scope.row.mg_state)'></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <!-- slot-scope="scope" -->
        <!-- slot-scope="scope" -->
        <!-- slot-scope="scope" -->
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top">
            <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="分类" placement="top">
            <el-button type="primary" icon="el-icon-share" @click="showRoleUser(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <el-button type="primary" icon="el-icon-delete" @click="delUser(scope.row.id)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="userobj.pagenum"
      :page-sizes="[1, 2, 3, 4]"
      :page-size="userobj.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogFormVisible">
      <el-form :model="addForm" :label-width="'120px'" :rules="rules" ref="addForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑用户的弹出对话框 -->
    <el-dialog title="编辑用户" :visible.sync="editUserDialogFormVisible">
      <el-form :model="editUsersForm" :label-width="'200px'" :rules="rules" ref="editUsersForm">
        <el-form-item label="用户名">
          <el-input
            v-model="editUsersForm.username"
            auto-complete="off"
            disabled
            style="width:80px"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="editUsersForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户手机" prop="mobile">
          <el-input v-model="editUsersForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 实现用户角色分配对话框的弹出 -->
    <el-dialog title="用户角色分配" :visible.sync="userRoleDialogFormVisible">
      <el-form :model="userRoleForm" :label-width="'80px'">
        <el-form-item label="用户名">
          <el-input v-model="userRoleForm.name" auto-complete="off" disabled style="width:80px"></el-input>
        </el-form-item>
        <el-form-item label="用户角色">
          <!-- <el-select v-model="userRoleForm.region" placeholder="请选择用户角色"> -->
          <el-select v-model="userRoleForm.rid" clearable placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.value"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
          <!-- </el-select> -->
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userRoleDialogFormVisible = false">取 消</el-button>
        <el-button type="primary"  @click="userRoleMethods">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllUsers,
  addUsers,
  editUsers,
  userRole,
  delUserById,
  userStatusChange
} from '@/api/user-index.js'
import { getAllRole } from '@/api/role-index.js'
// import axios from '@/utils/myaxios.js'
export default {
  data () {
    return {
      // 删除用户需要获取的数据
      delUserByIdForm: {

      },

      // 用户角色分配
      roleList: [],
      userRoleDialogFormVisible: false,
      userRoleForm: {
        name: '',
        id: '',
        rid: ''
      },

      // 编辑用户
      editUserDialogFormVisible: false,
      editUsersForm: {
        id: '',
        email: '',
        mobile: '',
        username: ''
      },
      // 添加用户的dailog对话框
      addDialogFormVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户rules规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入正确的邮箱', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      },
      total: 0,
      // xhr.status:获取当前服务器的响应状态  200=>成功
      userList: [],
      userobj: {
        query: '',
        pagenum: 1,
        pagesize: 2
      }
    }
  },
  methods: {
    handleSizeChange (val) {
      this.userobj.pagesize = val
      this.init()
    },
    handleCurrentChange (val) {
      this.userobj.pagenum = val
      this.init()
    },
    init () {
      getAllUsers(this.userobj)
        .then(res => {
          if (res.data.meta.status === 200) {
            this.userList = res.data.data.users
            // 获取记录总数
            this.total = res.data.data.total
          } else if (res.data.meta.status === 400) {
            this.$message.error(res.data.meta.msg)
            this.$router.push({ name: 'login' })
          }
        })
        .catch(() => {
          this.$message.warning('获取用户失败')
        })
    },
    // 新增用户
    add () {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          addUsers(this.addForm)
            .then(res => {
              // console.log(res)
              if (res.data.meta.status === 201) {
                this.$message.success('新增用户成功')
                this.addDialogFormVisible = false
                // 清空表单元素的数据--重置表单元素
                this.$refs.addForm.resetFields()
              }
            })
            .catch(() => {
              this.$message.warnimg('新增用户失败')
            })
        } else {
          this.$message.warning('请输入所有必填数据')
        }
      })
    },

    // 弹出编辑用户对话框
    showEditDialog (row) {
      this.editUserDialogFormVisible = true
      // console.log(row)
      this.editUsersForm.id = row.id
      this.editUsersForm.email = row.email
      this.editUsersForm.username = row.username
      this.editUsersForm.mobile = row.mobile
    },

    // 实现编辑用户的操作
    editUser () {
      editUsers(this.editUsersForm)
        .then(res => {
          if (res.data.meta.status === 200) {
            this.$message.success('编辑用户成功')
            // 刷新页面
            this.init()
            // 关闭弹框
            this.editUserDialogFormVisible = false
            // 重置弹框表单
            this.$refs.editUsersForm.resetFields()
          }
        })
        .catch(() => {
          this.$message.warning('编辑用户失败')
        })
    },

    // 实现点击分类弹出dialog
    showRoleUser (row) {
      // console.log(row)
      this.userRoleDialogFormVisible = true
      this.userRoleForm.name = row.username
      this.userRoleForm.id = row.id
      this.userRoleForm.rid = row.rid
    },

    // 实现用户角色分配
    userRoleMethods () {
      console.log(this.userRoleForm)
      if (this.userRoleForm.rid) {
        userRole(this.userRoleForm)
          .then(res => {
            if (res.data.meta.status === 200) {
              this.$message.success('角色分配成功')
              // 刷新页面
              this.init()
              // 关闭弹框
              this.userRoleDialogFormVisible = false
            }
          })
          .catch(() => {
            this.$message.success('角色分配失败')
          })
      } else {
        this.$message.warning('角色分配失败')
      }
    },

    // 实现删除用户功能
    delUser (id) {
      this.$confirm('此操作将永久删除用户,是否执行此操作?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delUserById(id)
            .then((res) => {
              if (res.data.meta.status === 200) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
                this.userobj.pagenum = Math.ceil((this.total - 1) / this.userobj.pagesize) < this.userobj.pagenum ? --this.userobj.pagenum : this.userobj.pagenum
                this.init()
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.meta.msg
                })
              }
            })
            .catch(() => {
              this.$message({
                type: 'error',
                message: '删除失败'
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 实现用户状态的更改
    changeState (id, type) {
      // console.log(id, type)
      userStatusChange(id, type)
        .then((res) => {
          if (res.data.meta.status === 200) {
            this.$message.success(res.data.meta.msg)
          } else {
            this.$message.warning('更改用户状态失败')
          }
        })
        .catch(() => {
          this.$message.warning('更改用户状态失败')
        })
    }

  },

  // -------------
  mounted () {
    this.init()
    getAllRole()
      .then((res) => {
        if (res.data.meta.status === 200) {
          this.roleList = res.data.data
        }
      })
      .catch(() => {
        this.$message.warning('获取角色失败')
      })
    // ----------
    // axios({
    //   url: 'users',
    //   params: this.userobj
    // })
    //   .then((res) => {
    //     console.log(res)
    //     if (res.data.meta.status === 200) {
    //       this.userList = res.data.data.users
    //       // 获取记录总数
    //       this.total = res.data.data.total
    //     } else if (res.data.meta.status === 400) {
    //       this.$message.error(res.data.meta.msg)
    //       this.$router.push({ name: 'login' })
    //     }
    //   })
    //   .catch(function (error) {
    //     console.log(error)
    //   })
  }
}
</script>

<style lang="less">
</style>
